/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:张熳
 * Date:2025-10-23
 * Time:17:30
 */
public class MyQueue implements IQueue{
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode first;//队头
    public ListNode last;//队尾

    public int usedSize;//记录队列中有效元素个数

    //检测队列是否是空
    public boolean isEmpty() {
        return usedSize == 0;
        //return first == null;
    }

    @Override
    public boolean offer(int val) {
        ListNode node = new ListNode(val);
        if (isEmpty()) {
            first = last = node;
        }else {
            last.next = node;
            node.prev = last;
            last = last.next;
        }
        usedSize++;
        return true;
    }

    @Override
    public int poll() {
        if (isEmpty()) {
            return -1;//这里不需要像栈等用异常类进行判空，因为源码中的poll也没有
        }
        int val = first.val;
        first = first.next;
        if (first != null) {
            first.prev = null;
        }
        usedSize--;
        return val;
    }

    @Override
    public int peek() {
        if (isEmpty()) {
            return -1;
        }
        return first.val;
    }

    //获取队列中有效元素个数
    public int size() {
        return this.usedSize;
    }
}
